1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 import java.lang.annotation.Annotation;
35 import java.lang.annotation.ElementType;
36 import java.lang.annotation.Retention;
37 import java.lang.annotation.RetentionPolicy;
38 import java.lang.annotation.Target;
39 import java.lang.reflect.Method;
40 import java.security.Permission;
41 import java.security.Policy;
42 import java.security.ProtectionDomain;
43
44 @Retention(RetentionPolicy.RUNTIME)
45 @Target({ ElementType.FIELD, ElementType.PARAMETER })
46 @interface Named {
47 String value();
48 }
49
50 public class ParameterAnnotations {
51
52
53
54 static class MyPolicy extends Policy {
55 final Policy defaultPolicy;
56 MyPolicy(Policy defaultPolicy) {
57 this.defaultPolicy = defaultPolicy;
58 }
59 public boolean implies(ProtectionDomain pd, Permission p) {
60 return p.getName().equals("setSecurityManager") ||
61 defaultPolicy.implies(pd, p);
62 }
63 }
64
65 public void nop(@Named("foo") Object foo,
66 @Named("bar") Object bar) {
67 }
68
69 void test(String[] args) throws Throwable {
70
71 test1();
72
73
74 Policy defaultPolicy = Policy.getPolicy();
75 Policy.setPolicy(new MyPolicy(defaultPolicy));
76 System.setSecurityManager(new SecurityManager());
77 try {
78 test1();
79 } finally {
80 System.setSecurityManager(null);
81 Policy.setPolicy(defaultPolicy);
82 }
83 }
84
85 void test1() throws Throwable {
86 for (Method m : thisClass.getMethods()) {
87 if (m.getName().equals("nop")) {
88 Annotation[][] ann = m.getParameterAnnotations();
89 equal(ann.length, 2);
90 Annotation foo = ann[0][0];
91 Annotation bar = ann[1][0];
92 equal(foo.toString(), "@Named(value=foo)");
93 equal(bar.toString(), "@Named(value=bar)");
94 check(foo.equals(foo));
95 check(! foo.equals(bar));
96 }
97 }
98 }
99
100
101 volatile int passed = 0, failed = 0;
102 void pass() {passed++;}
103 void fail() {failed++; Thread.dumpStack();}
104 void fail(String msg) {System.err.println(msg); fail();}
105 void unexpected(Throwable t) {failed++; t.printStackTrace();}
106 void check(boolean cond) {if (cond) pass(); else fail();}
107 void equal(Object x, Object y) {
108 if (x == null ? y == null : x.equals(y)) pass();
109 else fail(x + " not equal to " + y);}
110 static Class<?> thisClass = new Object(){}.getClass().getEnclosingClass();
111 public static void main(String[] args) throws Throwable {
112 try {thisClass.getMethod("instanceMain",String[].class)
113 .invoke(thisClass.newInstance(), (Object) args);}
114 catch (Throwable e) {throw e.getCause();}}
115 public void instanceMain(String[] args) throws Throwable {
116 try {test(args);} catch (Throwable t) {unexpected(t);}
117 System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
118 if (failed > 0) throw new AssertionError("Some tests failed");}
119 }